<template>
  <el-dialog v-model="visible" :title="title" width="50%">
    <el-form :model="form">
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="届数" :label-width="formLabelWidth">
        <el-input v-model="form.edition" />
      </el-form-item>
      <el-form-item label="任职单位职务与职称" :label-width="formLabelWidth">
        <el-input v-model="form.unitPosition" />
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth">
        <el-input v-model="form.sort" />
      </el-form-item>
      <el-form-item label="工作单位" :label-width="formLabelWidth">
        <el-input v-model="form.workUnit" />
      </el-form-item>
      <el-form-item label="个人简介" :label-width="formLabelWidth">
        <el-input v-model="form.introduction" type="textarea" />
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input v-model="form.remarks" type="textarea" />
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/upload"
           :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage,UploadProps } from "element-plus";
import type ResultType from "../../type/ResultType.ts";
import {instance} from "../request.js";

const visible = ref(false)
const formLabelWidth = '140px'
const title = ref('新增')

// 表单默认值
let defaultForm = {
  id: '',
  userName: '',
  edition: '',
  unitPosition: '',
  sort: '',
  avatar:"",
  workUnit: '',
  introduction: '',
  remarks: '',
  status: 1,
}

let form = ref(defaultForm)

// 重置表单
function resetForm() {
  form.value = structuredClone(defaultForm)
}

// 根据id查询数据
async function getById(id: number) {
  try {
    let result: ResultType = await instance.get('/bsAssociationCouncils/' + id)
    let { code, data, msg } = result.data
    if (code == 200) {
      return data
    }
    ElMessage({ message: msg, type: 'warning', })
  } catch (e) {
    console.log(e)
    ElMessage({ message: '查询数据失败', type: 'warning', })
  }
}

// 声明需要监听的父组件事件
const emit = defineEmits(['refresh'])

// 提交表单
async function submitForm() {
  //判断是新增还是编辑
  try {
    let result: ResultType
    if (form.value.id) {
      result = await instance.put('/bsAssociationCouncils/'+ form.value.id, form.value)
    }else{
      result = await instance.post('/bsAssociationCouncils', form.value)
    }
    let { code,data, msg } = result.data
    if (code == 200) {
      ElMessage({ message: data, type: 'success', })
      visible.value = false
      emit('refresh')
      return
    }
    ElMessage({ message: msg, type: 'warning', })
  } catch (e) {
    console.log(e)
    ElMessage({ message: '保存/更新数据失败', type: 'warning', })
  }
}

// add方法
function add() {
  resetForm()
  title.value = '新增'
  visible.value = true
}

// 编辑的方法
async function edit(row: any) {
  title.value = '编辑'
  visible.value = true
  form.value = await getById(row.id)
  console.log("表单数据"+form.value)
}

// 暴露给外面使用
defineExpose({
  add,
  edit,
})
import { Plus } from '@element-plus/icons-vue'

//头像上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  form.value.avatar = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//token
const headers = ref({
  "token":localStorage.getItem('token')
})
</script>

<style lang="scss" scoped>
  .avatar-uploader .avatar {
  width: 120px;
  height: 120px;
    display: block;
  }
  .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>